<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="75px">
      <!--<el-form-item label="所属课程" prop="platformId" v-if="!platformId">
        <el-select v-model="queryParams.platformId" @change="getChapterList(queryParams.platformId)"
          placeholder="请选择课程">
          <el-option v-for="item in platformList" :key="item.baseId" :label="item.title" :value="item.baseId">
            <span style="float: left">{{ item.title }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              <dict-tag :options="dict.type.bmzt" :value="item.applyStatus" />
            </span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属章节" prop="chapterId">
        <el-select v-model="queryParams.chapterId" placeholder="请选择章节" clearable>
          <el-option v-for="item in chapterList" :key="item.baseId" :label="item.title" :value="item.baseId">
            <span style="float: left">{{ item.title }}</span>
          </el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item label="视频标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入视频标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:platformVideo:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:platformVideo:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:platformVideo:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['business:platformVideo:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="platformVideoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="baseId" v-if="false" />
<!--      <el-table-column label="所属课程" align="center" prop="platformTitle" :show-overflow-tooltip="true" />-->
<!--      <el-table-column label="所属章节" align="center" prop="chapterTitle" :show-overflow-tooltip="true" />-->
      <el-table-column label="视频标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="视频时长(秒)" align="center" prop="duration" />
      <el-table-column label="观看程度(%)" align="center" prop="degree" />
      <el-table-column label="积分数" align="center" prop="points" />
<!--      <el-table-column label="排序" align="center" prop="sort" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:platformVideo:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:platformVideo:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改视频管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" @close="cancel" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--<el-form-item label="所属课程" prop="platformId" v-if="!platformId">
          <el-select v-model="form.platformId" @change="getChapterList(form.platformId)" placeholder="请选择课程">
            <el-option v-for="item in platformList" :key="item.baseId" :label="item.title" :value="item.baseId">
              <span style="float: left">{{ item.title }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                <dict-tag :options="dict.type.bmzt" :value="item.applyStatus" />
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属章节" prop="chapterId">
          <el-select v-model="form.chapterId" placeholder="请选择章节">
            <el-option v-for="item in chapterList" :key="item.baseId" :label="item.title" :value="item.baseId">
            </el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="视频封面">
          <image-upload v-model="form.coverUrl" :limit="1"/>
        </el-form-item>
        <el-form-item label="视频" prop="videoId">
          <!--阿里云播放器-->
          <ali-player :encryptType="0" :vid="form.videoId" :playauth="form.playAuth" ref="player" :useFlashPrism="false"
            :autoplay="false" :isLive="false" :showBuffer="true" :cover="form.coverUrl" :showBarTime="true"
            :disableSeek="false" :isFast="true" showBarTime="500" width="800px" controlBarVisibility="always">
          </ali-player>
        </el-form-item>
        <el-form-item label="视频时长" prop="duration">
          <el-input v-model="form.duration" @input="(v)=>(form.degree=v.replace(/[^\d.]/g,''))" disabled
            placeholder="请输入视频时长(秒)">
            <template slot="append">秒</template>
          </el-input>
        </el-form-item>
        <el-form-item label="观看程度" prop="degree">
          <el-input v-model="form.degree" @input="(v)=>(form.degree=v.replace(/[^\d.]/g,''))" placeholder="请输入观看程度">
            <template slot="append">%</template>
          </el-input>
          <el-tag type="warning">观看程度达到设定的值，可视为本视频已全部学完</el-tag>
        </el-form-item>
        <el-form-item label="积分数" prop="points">
          <el-input v-model="form.points" @input="(v)=>(form.points=v.replace(/[^\d.]/g,''))" placeholder="请输入积分数">
            <template slot="append">分</template>
          </el-input>
          <el-tag type="warning">观看本视频可得积分</el-tag>
        </el-form-item>
<!--        <el-form-item label="排序">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>-->
        <el-form-item label="允许快进" prop="allowFast">
          <el-switch v-model="form.allowFast"></el-switch>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 视频导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :file-list="fileList" :limit="1" accept=".mp4" :headers="upload.headers"
        :action="upload.url" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许上传mp4格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import VueAliplayer from "../../../components/AliPlayer";
  import axios from 'axios'
  import {
    listPlatformVideo,
    getPlatformVideo,
    delPlatformVideo,
    addPlatformVideo,
    updatePlatformVideo
  } from "@/api/business/platformVideo";
  import {
    platformList
  } from "@/api/business/platform";
  import {
    chapterList
  } from "@/api/business/platformChapter";
  import {
    getToken
  } from "@/utils/auth";

  export default {
    name: "PlatformVideo",
    dicts: ['bmzt'],
    components: {
      "ali-player": VueAliplayer
    },
    props: {
      /*platformId: {
        type: String,
        default: ""
      },*/
      activeName: {
        type: String,
        default: ""
      },
    },
    watch: {
      activeName: {
        handler: function(val, oldVal) {
          // this.queryParams.platformId = this.platformId;
          if (val === 'third') {
            this.getList();
            // this.getChapterList(this.platformId);
          }
        },
        immediate: true
      }
    },
    data() {
      return {
        visible: false,
        // 课程列表
        // platformList: [],
        // 章节列表
        // chapterList: [],

        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 视频管理表格数据
        platformVideoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: undefined,
          // platformId: this.platformId,
          // chapterId: undefined,
        },
        fileList: [],
        // 导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/aliVod/aliVodUpload"
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          /*platformId: [{
            required: true,
            message: "课程不能为空",
            trigger: "blur"
          }],
          chapterId: [{
            required: true,
            message: "章节不能为空",
            trigger: "blur"
          }],*/
          title: [{
            required: true,
            message: "视频标题不能为空",
            trigger: "blur"
          }],
          duration: [{
            required: true,
            message: "视频时长(秒)不能为空",
            trigger: "blur"
          }],
          degree: [{
            required: true,
            message: "观看程度(%)不能为空",
            trigger: "blur"
          }],
          points: [{
            required: true,
            message: "积分数不能为空",
            trigger: "blur"
          }],
          allowFast: [{
            required: true,
            message: "是否允许快进不能为空",
            trigger: "blur"
          }],
        }
      };
    },
    created() {
      this.getList();
      // this.getPlatformList();
    },
    methods: {
      uploadFile() {
        this.visible = true;
      },
      onClose() {
        this.visible = false;
      },
      /*getPlatformList() {
        platformList().then(response => {
          this.platformList = response.data;
        });
      },
      getChapterList(platformId) {
        this.form.chapterId = '';
        chapterList({
          platformId: platformId
        }).then(response => {
          this.chapterList = response.data;
        });
      },*/
      /** 查询视频管理列表 */
      getList() {
        this.loading = true;
        listPlatformVideo(this.queryParams).then(response => {
          this.platformVideoList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.$refs.player.pause()
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          baseId: undefined,
          // platformId: this.platformId,
          // chapterId: undefined,
          title: undefined,
          videoId: undefined,
          playAuth: undefined,
          coverUrl: undefined,
          duration: undefined,
          degree: undefined,
          points: undefined,
          allowFast: false,
          // sort: undefined,
          delFlag: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.baseId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 导入按钮操作 */
      handleAdd() {
        this.upload.title = "上传视频";
        this.fileList = []
        this.upload.open = true;
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response
          .msg + "</div>", "导入结果", {
            dangerouslyUseHTMLString: true
          });
        this.getList();
      },
      submitFileForm() {
        this.$refs.upload.submit();
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        const baseId = row.baseId || this.ids
        getPlatformVideo(baseId).then(response => {
          this.loading = false;
          this.form = response.data.videoVo;
          this.open = true;
          this.$refs.player.replayByVidAndPlayAuth(this.form.videoId, this.form.playAuth)
          this.title = "修改视频管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.coverUrl === "") {
              this.form.coverUrl = null;
            }
            if (this.form.baseId != null) {
              updatePlatformVideo(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addPlatformVideo(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const baseIds = row.baseId || this.ids;
        this.$modal.confirm('是否确认删除视频管理编号为"' + baseIds + '"的数据项？').then(() => {
          this.loading = true;
          return delPlatformVideo(baseIds);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {}).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('business/platformVideo/export', {
          ...this.queryParams
        }, `platformVideo_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
